//
//  onNetwork.m
//  10-10
//
//  Created by 钟纪旺 on 16/11/15.
//  Copyright © 2016年 zjw. All rights reserved.
//

#import "Network.h"

@implementation Network
+ (void)loginWithName:(NSString *)name password:(NSString *)password  complete:(void (^)(LoginData *))handle
{
    NSDictionary *param = @{
                            @"name":name,
                            @"password":password
                            };
    [self getDataWithParam:param urlString:@"http://xl18z.cn/login.php" dataClass:[LoginData class]  complete:^(id data) {
        handle(data);
    }];
}

+ (void)loginWithName:(NSString *)name password:(NSString *)password tel:(NSString *)tel complete:(void (^)(LoginData *))handle{

    NSDictionary *param = @{
                            @"name":name,
                            @"password":password,
                            @"tel":tel
                            };
    [self getDataWithParam:param urlString:@"http://xl18z.cn/node/reg" dataClass:[LoginData class] complete:^(id data) {
        handle(data);
    }];



}
+ (void)getDataWithParam:(NSDictionary *)param urlString:(NSString *)urlString dataClass:(Class)cls complete:(void (^)(id data))handle
{
    
    NSMutableString *str = [[NSMutableString alloc] initWithString:urlString];
    [str appendString:@"?"];
    for(NSString *key in param){
        [str appendFormat:@"%@=%@&",key,param[key]];
    }
    NSString *str2 = [str substringToIndex:str.length - 1];
    NSLog(@"url:%@",str2);
    NSURL *url = [NSURL URLWithString:str2];
    
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"----->%@",[[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding]);
        dispatch_async(dispatch_get_main_queue(), ^{
            handle([[cls alloc]initWithDictionary:dict]);
        });
        
    }];
    [task resume];
}

@end
